﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.SessionState;

namespace RDIFramework.WebApp.Modules.handler
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.ServiceAdapter;
    using RDIFramework.Utilities;
    using RDIFramework.WebCommon;


    /// <summary>
    /// RoleAdminHandler 的摘要说明
    /// 
    /// 修改说明：
    ///     2013-07-25 EricHu 新增：GetRoleListByPage。
    /// </summary>
    public class RoleAdminHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 权限域（范围权限、数据权限）
        /// </summary>
        private string PermissionItemScopeCode = "Resource.ManagePermission";

        private string action
        {
            get
            {
                return RDIFramework.WebCommon.PublicMethod.GetString(getObj("action"));
            }
        }

        private object getObj(string key) { return RDIFramework.WebCommon.StringHelper.GetRequestObject(key); }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            switch (action)
            {
                case "add":
                    AddRole(context);
                    break;
                case "edit":
                    EditRole(context);
                    break;
                case "delete":
                    DeleteRole(context);
                    break;
                case "usersinrole":
                    UserInRole(context);
                    break;
                case "setusers":
                    SetUsers(context);
                    break;
                case "removeuserfromrole": //将用户从角色中移除
                    RemoveUserFromRole(context);
                    break;
                case "AddUserToRole": //用户添加到角色
                    AddUserToRole(context);
                    break;
                case "getrolelist":
                    GetRoleList(context);
                    break;
                case "GetEnabledRoleList":  //得到有效的角色列表
                    GetEnabledRoleList(context);
                    break;
                case "GetRoleListByPage":
                    GetRoleListByPage(context);
                    break;
                case "GetRoleListByUserId": //得到当前用户所拥有的角色列表
                    GetRoleListByUserId(context);
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region private void AddRole(HttpContext ctx) 新增角色
        private void AddRole(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            PiRoleEntity entity = new PiRoleEntity();
            entity.Code = PublicMethod.GetString(getObj("rolecode"));
            entity.RealName = PublicMethod.GetString(getObj("rolename"));
            entity.Category = PublicMethod.GetString(getObj("category"));
            entity.Enabled = PublicMethod.GetString(getObj("enabled")) == "checked" ? 1 : 0;
            entity.Description = PublicMethod.GetString(getObj("description"));
            entity.DeleteMark = 0;
            entity.AllowDelete = 1;
            entity.AllowEdit = 1;
            if (vUser != null)
            {
                entity.CreateBy = vUser.RealName;
                entity.CreateUserId = vUser.Id;
            }
            string statusMessage = string.Empty;
            string statusCode = string.Empty;

            try
            {
                 RDIFrameworkService.Instance.RoleService.Add(vUser, entity, out statusCode, out statusMessage);
                if (statusCode == StatusCode.OKAdd.ToString())
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write(statusMessage);
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write("新增角色失败，错误信息为：" +ex.Message);
            }  
        }
        #endregion

        #region private void EditRole(HttpContext ctx) 修改角色
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="ctx"></param>
        private void EditRole(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("roleid"));
            PiRoleEntity entity = RDIFrameworkService.Instance.RoleService.GetEntity(vUser, vId);
            if (entity != null)
            {
                entity.Code = PublicMethod.GetString(getObj("rolecode"));
                entity.RealName = PublicMethod.GetString(getObj("rolename"));
                entity.Category = PublicMethod.GetString(getObj("category"));
                entity.Enabled = PublicMethod.GetString(getObj("enabled")) == "checked" ? 1 : 0;
                entity.Description = PublicMethod.GetString(getObj("description"));
            }

            if (vUser != null)
            {
                entity.ModifiedBy = vUser.RealName;
                entity.ModifyUserId = vUser.Id;
            }

            try
            {
                string statusCode = string.Empty;
                string statusMessage = string.Empty;
                RDIFrameworkService.Instance.RoleService.Update(vUser, entity, out statusCode, out statusMessage);
                if (statusCode == StatusCode.OKUpdate.ToString())
                {
                    if (SystemInfo.ShowInformation)
                    {
                        ctx.Response.Write("1");
                    }
                }
                else
                {
                    ctx.Response.Write(statusMessage);
                }
            }
            catch (Exception ex)
            {
                ctx.Response.Write("修改角色失败，错误信息为：" + ex.Message);
            }
        }
        #endregion

        #region private void DeleteRole(HttpContext ctx) 删除角色
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ctx"></param>
        private void DeleteRole(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string vId = PublicMethod.GetString(getObj("roleid"));
            int vReturnValue = RDIFrameworkService.Instance.RoleService.SetDeleted(vUser, new string[] { vId });
            if (vReturnValue > 0)
            {
                ctx.Response.Write("1");
            }
            else
            {
                ctx.Response.Write("删除角色失败！");
            }
        }
        #endregion

        private void UserInRole(HttpContext ctx)
        {
            DataTable dtUser = new DataTable(PiUserTable.TableName);
            string vId = PublicMethod.GetString(getObj("roleid"));
            dtUser = RDIFrameworkService.Instance.UserService.GetDTByRole(Utils.UserInfo, vId);
            ctx.Response.Write(RDIFramework.WebCommon.JSONhelper.ToJson(dtUser));
        }

        private void SetUsers(HttpContext ctx)
        {
            string vRoleId = PublicMethod.GetString(getObj("roleid"));
            string userIds = PublicMethod.GetString(getObj("users"));
            if (!string.IsNullOrEmpty(userIds) && userIds.Length > 0)
            {
                int iReturnValue = RDIFrameworkService.Instance.RoleService.AddUserToRole(Utils.UserInfo, vRoleId, userIds.Split(','));
                if (iReturnValue > 0)
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write("添加用户到角色失败！");
                }
            }
        }

        /// <summary>
        /// 将用户从角色中移除
        /// </summary>
        /// <param name="ctx"></param>
        private void RemoveUserFromRole(HttpContext ctx)
        {
            string vRoleId = PublicMethod.GetString(getObj("roleid"));
            string userId = PublicMethod.GetString(getObj("uid"));

            if (!string.IsNullOrEmpty(userId) && userId.Length > 0)
            {
                int iReturnValue = RDIFrameworkService.Instance.RoleService.RemoveUserFromRole(Utils.UserInfo, vRoleId, new string[] { userId });
                if (iReturnValue > 0)
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write("用户移除角色失败！");
                }
            }
        }

        /// <summary>
        /// 用户添加到角色
        /// </summary>
        /// <param name="ctx"></param>
        private void AddUserToRole(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleId"));
            string addUserIds = PublicMethod.GetString(getObj("addUserIds"));

            if (!string.IsNullOrEmpty(addUserIds) && addUserIds.Trim().Length > 0)
            {
                int returnValue = RDIFrameworkService.Instance.RoleService.AddUserToRole(Utils.UserInfo, roleId, addUserIds.Split(','));
                if(returnValue > 0)
                {
                    ctx.Response.Write("1");
                }
                else
                {
                    ctx.Response.Write("添加角色失败！");
                }
            }
        }

        /// <summary>
        /// 得到角色Json列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetRoleList(HttpContext ctx)
        {
            ctx.Response.Write(RDIFramework.WebCommon.JSONhelper.ToJson(this.GetRoleScope(this.PermissionItemScopeCode)));
        }

        /// <summary>
        /// 得到有效的角色列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetEnabledRoleList(HttpContext ctx)
        {
            string returnJson = "[]";
            DataTable DTRole = RDIFrameworkService.Instance.RoleService.GetDTByValues(Utils.UserInfo, new string[] { "DeleteMark", "Enabled" }, new string[] { "0", "1" });
            if(DTRole != null && DTRole.Rows.Count >0)
            {
                returnJson = RDIFramework.WebCommon.JSONhelper.ToJson(DTRole);
            }
            ctx.Response.Write(returnJson);

        }

        /// <summary>
        /// 得到指定用户所拥有的角色列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetRoleListByUserId(HttpContext ctx)
        {
            UserInfo vUser = Utils.UserInfo;
            string userId = PublicMethod.GetString(getObj("userId"));
            string[] roleIds = RDIFrameworkService.Instance.UserService.GetUserRoleIds(vUser, userId);
            string writeJson = "[]";
            if (roleIds != null && roleIds.Length > 0)
            {
                writeJson = RDIFramework.WebCommon.JSONhelper.ToJson(RDIFrameworkService.Instance.RoleService.GetDTByIds(vUser, roleIds));
            }
            ctx.Response.Write(writeJson);
        }

        /// <summary>
        /// 获取角色权限域数据
        /// </summary>
        private DataTable GetRoleScope(string permissionItemScopeCode)
        {
            UserInfo vUser = Utils.UserInfo;
            // 获取部门数据
            DataTable returnValue = new DataTable(PiRoleTable.TableName);
            if ((vUser.IsAdministrator) || (String.IsNullOrEmpty(permissionItemScopeCode) || (!SystemInfo.EnableUserAuthorizationScope)))
            {
                returnValue = RDIFrameworkService.Instance.RoleService.GetDT(vUser);
            }
            else
            {
                returnValue = RDIFrameworkService.Instance.PermissionService.GetRoleDTByPermissionScope(vUser, vUser.Id, permissionItemScopeCode);
            }
            return returnValue;
        }


        //每页的记录数
        private int pagesize { get { return PublicMethod.GetInt(getObj("rows")); } }
        //当前请求第几页
        private int pageindex { get { return PublicMethod.GetInt(getObj("page")); } }
        //排序字段
        public string sortName { get { return PublicMethod.GetString(getObj("sort")); } }
        //排序方式
        public string sortType { get { return PublicMethod.GetString(getObj("order")); } }
        /// <summary>
        /// 得到分页角色列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetRoleListByPage(HttpContext ctx)
        {
            string where = "";
            string filters = PublicMethod.GetString(getObj("filter"));
            if (filters != "")
            {
                string grouptype;
                IList<SearchFilter> list = SearchFilter.GetSearchList(filters, out grouptype);
                where = SearchFilter.ToSql(list, grouptype);
            }

            int _pageindex = 1;
            int _pagesize = 20;

            if (pageindex > 0)
                _pageindex = pageindex;
            if (pagesize > 0)
                _pagesize = pagesize;
            int recordCount = 0;
            DataTable dtRole = RDIFramework.ServiceAdapter.RDIFrameworkService.Instance.RoleService.GetDTByPage(Utils.UserInfo, out recordCount, _pageindex, _pagesize, where, (sortName + " " + sortType));
            string json = RDIFramework.WebCommon.JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dtRole);
            ctx.Response.Write(json);
        }
    }
}